<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-button type="primary"
                   @click="addContractDialog()">
          添加合同
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   :loading="downloadLoading"
                   @click="exportContract()">
          导出EXCEL
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading"
              :data="tableData"
              border
              stripe
              style="width: 100%"
              @sort-change="sortChange">
      <el-table-column prop="id"
                       label="ID"
                       width="100"
                       align="center"
                       fixed
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column prop="code"
                       label="编号"
                       width="150"
                       align="center"
                       fixed
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column prop="name"
                       label="合同名称"
                       min-width="400"
                       align="center"
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="type"
                       label="合同类型"
                       width="150"
                       align="center"
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.typeName }}
        </template>
      </el-table-column>
      <el-table-column prop="department_id"
                       label="所属部门"
                       width="150"
                       align="center"
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.department.name }}
        </template>
      </el-table-column>
      <el-table-column prop="client_company"
                       label="委托方"
                       width="300"
                       align="center"
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.clientCompany }}
        </template>
      </el-table-column>
      <el-table-column prop="consult_company"
                       label="咨询方"
                       width="300"
                       align="center"
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.consultCompany }}
        </template>
      </el-table-column>
      <el-table-column prop="received_time"
                       label="收到日期"
                       width="150"
                       align="center"
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.receivedTime }}
        </template>
      </el-table-column>
      <el-table-column prop="record_id"
                       label="录入人"
                       width="150"
                       align="center"
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.recorder.realname }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at"
                       label="创建时间"
                       width="200"
                       align="center"
                       sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.createdAt }}
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       fixed="right"
                       width="200"
                       align="center">
        <template slot-scope="scope">
          <el-button type="text"
                     @click="editContractDialog(scope.row)">编辑</el-button>
          <el-button type="text"
                     @click="uploadContractDialog(scope.row)">附件</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加合同"
               width="50%"
               :visible.sync="dialogAddContractVisible">
      <add-contract ref="addContract"
                    style="margin-left:30px;"
                    :department-item="departmentItem"
                    :type-item="typeItem"
                    :loading="loadingAddContract"
                    :organ-data="organData"
                    @submit="addContractInfo" />
    </el-dialog>

    <el-dialog title="编辑合同"
               width="50%"
               :visible.sync="dialogEditContractVisible">
      <edit-contract ref="editContract"
                     style="margin-left:30px;"
                     :row="row"
                     :department-item="departmentItem"
                     :type-item="typeItem"
                     :loading="loadingEditContract"
                     :organ-data="organData"
                     @submit="editContractInfo" />
    </el-dialog>

    <el-dialog title="附件管理"
               width="50%"
               :visible.sync="dialogUploadContractVisible"
               :destroy-on-close="true"
               @close="closeUploadDialog">
      <upload-contract style="margin-left:30px;"
                       :attach-list="attachList"
                       :attach-data="attachData"
                       @submit="handleSubmit" />
    </el-dialog>
  </div>
</template>

<script>
import { addContract, editContract, getContractData } from '@/api/contract'
import { getOrganData } from '@/api/dictionary'
import { parseTime } from '@/utils'
import AddContract from './components/add'
import EditContract from './components/edit'
import uploadContract from './components/upload'
export default {
  components: { AddContract, EditContract, uploadContract },
  props: {
    tableData: {
      default: () => [],
      type: Array
    },
    loading: {
      default: false,
      type: Boolean
    },
    departmentItem: {
      default: () => [],
      type: Array
    },
    typeItem: {
      default: () => [],
      type: Array
    },
    query: {
      default: null,
      type: Object
    }
  },
  data() {
    return {
      dialogAddContractVisible: false,
      dialogEditContractVisible: false,
      dialogUploadContractVisible: false,
      loadingAddContract: false,
      loadingEditContract: false,
      loadingUploadContract: false,
      downloadLoading: false,
      row: {
        id: null, departmentId: null, name: null, code: null, type: null,
        clientCompany: null, clientMan: null, clientPhone: null,
        consultCompany: null, consultMan: null, consultPhone: null,
        receivedTime: null, remark: null
      },
      attachList: [],
      attachData: { id: null, companyId: null, departmentId: null },
      organData: [],
      excelData: null
    }
  },
  methods: {
    handleSubmit() {
      this.$emit('submit')
    },
    sortChange(sort) {
      this.$emit('change', {
        field: sort.prop,
        rule: sort.order
      })
      this.$emit('submit')
    },
    addContractDialog() {
      this.dialogAddContractVisible = true
      this.getOrganData()
      this.$nextTick(() => {
        this.$refs.addContract.handleFormReset()
      })
    },
    editContractDialog(row) {
      this.dialogEditContractVisible = true
      this.$nextTick(() => {
        this.$refs.editContract.handleFormReset()
      })
      this.getOrganData()
      const { id, departmentId, name, code, type, clientCompany, clientMan, clientPhone, consultCompany, consultMan, consultPhone, receivedTime, remark } = row
      this.row = { id, departmentId, name, code, type, clientCompany, clientMan, clientPhone, consultCompany, consultMan, consultPhone, receivedTime, remark }
    },
    uploadContractDialog(row) {
      this.dialogUploadContractVisible = true
      this.attachList = row.attachList
      const { id, companyId, departmentId } = row
      this.attachData = { id, companyId, departmentId }
    },
    addContractInfo(form) {
      this.loadingAddContract = true
      addContract(form).then(res => {
        this.$message({
          message: '添加成功',
          type: 'success',
          duration: 3 * 1000
        })
        this.handleSubmit()
        this.loadingAddContract = false
        this.dialogAddContractVisible = false
      }).catch(err => {
        this.loadingAddContract = false
      })
    },
    editContractInfo(form) {
      this.loadingEditContract = true
      editContract(form).then(res => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 3 * 1000
        })
        this.handleSubmit()
        this.loadingEditContract = false
        this.dialogEditContractVisible = false
      }).catch(err => {
        this.loadingEditContract = false
      })
    },
    async exportContract() {
      this.downloadLoading = false
      this.excelData = await getContractData(this.query)
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序号', '编号', '委托方', '咨询方', '项目名称', '合同类型', '所属部门', '收到日期', '录入人', '备注']
        const filterVal = ['@id', 'code', 'clientCompany', 'consultCompany', 'name', 'typeName', 'department.name',
          'receivedTime', 'recorder.realname', 'remark']
        const list = this.excelData
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '合同',
          autoWidth: true,
          bookType: 'xlsx',
          sheetName: '合同'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      let i = 0
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'createdAt' || j === 'updatedAt') {
          return parseTime(v[j])
        }
        if (j.indexOf('.') != -1) {
          const tmp = j.split('.')
          return v[tmp[0]][tmp[1]]
        }
        if (j === '@id') {
          return ++i
        }
        return v[j]
      }))
    },
    closeUploadDialog(done) {
      this.attachList = []
      this.attachData = { id: null, companyId: null, departmentId: null }
    },
    async getOrganData() {
      this.organData = await getOrganData()
    }
  }
}
</script>

<style lang="scss">
.el-table th.gutter {
  display: table-cell !important;
}
.el-table td.is-center {
  top: 1px !important;
}
</style>
